﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CCWin.SkinClass;
using CCWin.SkinControl;
using ERPWinFormWork.Material.Material.Dtos;



namespace ERPWinFormWork.Material
{
    public partial class MaterialInput : Form
    {
        /// <summary>
        /// 获取是否添加成功的标志
        /// </summary>
        public bool IsAddSuccess => this.Tag?.ToString() == "Success";
        
        // 存储选中的物料ID和单位ID
        private int _selectedMaterialId;
        private int _selectedUnitId;
        
        // 存储选中的仓库ID和库区ID
        private int _selectedWarehouseId;
        private int _selectedAreaId;
        
        public MaterialInput()
        {
            InitializeComponent();
        }

        private void MaterialInput_Load(object sender, EventArgs e)
        {
            // 为复选框添加事件处理
            cbonumber.CheckedChanged += Cbonumber_CheckedChanged;
        }



        /// <summary>
        /// 复选框选中状态改变事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Cbonumber_CheckedChanged(object sender, EventArgs e)
        {
            if (cbonumber.Checked)
            {
                // 生成入库编号：RKBH + 年月日时分秒
                string rkNumber = GenerateRKBHNumber();
                tbxnumber.Text = rkNumber;
            }
            else
            {
                // 取消选中时清空入库编号
                tbxnumber.Text = "请输入";
            }
        }

        /// <summary>
        /// 生成入库编号
        /// 格式：RKBH + 年月日时分秒
        /// </summary>
        /// <returns>生成的入库编号</returns>
        private string GenerateRKBHNumber()
        {
            DateTime now = DateTime.Now;
            string timeStamp = now.ToString("yyyyMMddHHmmss");
            return "RKBH" + timeStamp;
        }
        /// <summary>
        /// 点击选择采购单信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelectProcurement_Click(object sender, EventArgs e)
        {
            PurchaseOrders orders = new PurchaseOrders();
            if (orders.ShowDialog() == DialogResult.OK)
            {
                // 获取选中的采购单数据
                var selectedItems = orders.GetSelectedItems();
                if (selectedItems != null && selectedItems.Count > 0)
                {
                    // 获取第一个选中的项目
                    var firstItem = selectedItems.First();
                    
                    // 将采购单号填充到采购单号文本框中
                    tbxid.Text = firstItem.Purchase_Number;
                    
                    // 将供应商名称填充到供应商文本框中
                    tbxsupplier.Text = firstItem.SupplierName;
                    
                    // 同时填充采购名称
                    tbxProcurementName.Text = firstItem.ContractName;
                    
                    // 显示选中的信息
                    MessageBox.Show($"已选择采购单：{firstItem.ContractName}\n采购单号：{firstItem.Purchase_Number}\n供应商：{firstItem.SupplierName}\n采购日期：{firstItem.SignDate:yyyy-MM-dd}", 
                        "选择完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    
                    // 如果选择了多个项目，可以在这里处理
                    if (selectedItems.Count > 1)
                    {
                        // 可以选择将多个采购单号用逗号分隔显示，或者只显示第一个
                        // tbxid.Text = string.Join(", ", selectedItems.Select(x => x.Purchase_Number));
                    }
                }
            }
        }
         /// <summary>
        /// 点击选择来料检验单信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnincoming_Click(object sender, EventArgs e)
        {
            IncomingOrder incomingOrder = new IncomingOrder();
            if (incomingOrder.ShowDialog() == DialogResult.OK)
            {
                // 获取选中的来料检验单数据
                var selectedItems = incomingOrder.GetSelectedItems();
                if (selectedItems != null && selectedItems.Count > 0)
                {
                    // 获取第一个选中的项目
                    var firstItem = selectedItems.First();
                    
                    // 将检验单号填充到来料检验单号文本框中
                    tbxorder.Text = firstItem.InspectionNode;
                    
                    // 同时填充来料检验名称
                    tbxordername.Text = firstItem.InspectionName;

                    // 填充物料相关信息
                    tbxmaterialname.Text = firstItem.MaterialName;           // 物料名称
                    tbxmaterialid.Text = firstItem.MaterialNumber;          // 物料编号
                    tbxspecifications.Text = firstItem.Specifications;      // 规格型号
                    tbxunit.Text = firstItem.UnitName;                     // 单位
                    
                    // 存储物料ID和单位ID到MaterialInputDtos中
                    if (firstItem.MaterialId.HasValue)
                    {
                        // 这里可以将物料ID存储到类的字段中，供后续使用
                        _selectedMaterialId = firstItem.MaterialId.Value;
                    }
                    
                    if (firstItem.Unit_Id.HasValue)
                    {
                        // 这里可以将单位ID存储到类的字段中，供后续使用
                        _selectedUnitId = firstItem.Unit_Id.Value;
                    }
                    
                    // 显示选中的信息
                    MessageBox.Show($"已选择检验单：{firstItem.InspectionName}\n检验单号：{firstItem.InspectionNode}\n物料：{firstItem.MaterialName}\n批次：{firstItem.Batch}", 
                        "选择完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    
                    // 如果选择了多个项目，可以在这里处理
                    if (selectedItems.Count > 1)
                    {
                        // 可以选择将多个检验单号用逗号分隔显示，或者只显示第一个
                        // tbxorder.Text = string.Join(", ", selectedItems.Select(x => x.InspectionNode));
                    }
                }
            }
        }
     
        /// <summary>
        ///  点击选择仓库信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnwares_Click(object sender, EventArgs e)
        {
            Warehouse warehouse = new Warehouse();
            if (warehouse.ShowDialog() == DialogResult.OK)
            {
                // 获取选中的仓库数据
                var selectedItems = warehouse.GetSelectedItems();
                if (selectedItems != null && selectedItems.Count > 0)
                {
                    // 获取第一个选中的项目
                    var firstItem = selectedItems.First();

                    // 将仓库名称填充到仓库名称文本框中
                    tbxwarehousename.Text = firstItem.Warehouse_Name;
                    tbxarea.Text = firstItem.Warehouse_Area;
                    tbxlocation.Text = firstItem.Storage_location;
                    
                    // 存储仓库ID和库区ID到MaterialInputDtos中
                    _selectedWarehouseId = firstItem.WarehouseId;
                    _selectedAreaId = firstItem.AreaId;

                    // 显示选中的信息
                    MessageBox.Show($"已选择仓库：{firstItem.Warehouse_Name}\n库位：{firstItem.Storage_location}\n库区：{firstItem.Warehouse_Area}",
                        "选择完成", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    // 如果选择了多个项目，可以在这里处理
                    if (selectedItems.Count > 1)
                    {
                        // 可以选择将多个仓库名称用逗号分隔显示，或者只显示第一个
                        // tbxwarehousename.Text = string.Join(", ", selectedItems.Select(x => x.Warehouse_Name));
                    }
                }
            }
        }
        /// <summary>
        /// 关闭按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnoff_Click(object sender, EventArgs e)
        {
            // 关闭当前窗体
            this.Close();
        }

        private async void btnAdd_Click(object sender, EventArgs e)
        {
            //初始化物料入库对象
            AddMaterialInputDtos materialInput = new AddMaterialInputDtos();

            // 基础校验
            if (string.IsNullOrWhiteSpace(tbxnumber.Text) || tbxnumber.Text == "请输入")
            {
                MessageBox.Show("入库编号不能为空!", "校验失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (string.IsNullOrWhiteSpace(tbxname.Text))
            {
                MessageBox.Show("入库单名称不能为空!", "校验失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (string.IsNullOrWhiteSpace(tbxProcurementName.Text))
            {
                MessageBox.Show("采购名称不能为空!", "校验失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (string.IsNullOrWhiteSpace(tbxid.Text))
            {
                MessageBox.Show("采购单号不能为空!", "校验失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (string.IsNullOrWhiteSpace(tbxordername.Text))
            {
                MessageBox.Show("来料检验名称不能为空!", "校验失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (string.IsNullOrWhiteSpace(tbxorder.Text))
            {
                MessageBox.Show("来料检验单号不能为空!", "校验失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (string.IsNullOrWhiteSpace(tbxmaterialname.Text))
            {
                MessageBox.Show("物料名称不能为空!", "校验失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (string.IsNullOrWhiteSpace(tbxwarehousename.Text))
            {
                MessageBox.Show("仓库名称不能为空!", "校验失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (string.IsNullOrWhiteSpace(dtpcount.Text))
            {
                MessageBox.Show("入库数量不能为空!", "校验失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 赋值基础信息
            materialInput.WarehouseReceiptNumber = tbxnumber.Text ?? string.Empty;
            materialInput.WarehouseReceiptName = tbxname.Text ?? string.Empty;
            materialInput.WarehousingDate = DateTime.Now; // 直接使用当前时间
            
            // 采购相关信息 - 从btnSelectProcurement_Click获取
            materialInput.PurchaseOrdersNumber = tbxid.Text ?? string.Empty;
            materialInput.SupplierName = tbxsupplier.Text ?? string.Empty;
            materialInput.PurchaseOrdersName = tbxProcurementName.Text ?? string.Empty; // 采购单名称
            materialInput.PurchaseOrdersName_Id = !string.IsNullOrWhiteSpace(tbxProcurementName.Text) ? 
                (int?)GetIdFromText(tbxProcurementName.Text) : null;
            
            // 来料检验相关信息 - 从btnincoming_Click获取
            materialInput.IncomingNumber = tbxorder.Text ?? string.Empty;
            materialInput.IncomingName = tbxordername.Text ?? string.Empty; // 来料检验单名称
            materialInput.IncomingName_Id = !string.IsNullOrWhiteSpace(tbxordername.Text) ? 
                (int?)GetIdFromText(tbxordername.Text) : null;
            
            // 物料详细信息 - 从btnincoming_Click获取
            materialInput.MaterialNumber = tbxmaterialid.Text ?? string.Empty;
            materialInput.MaterialName = tbxmaterialname.Text ?? string.Empty;
            materialInput.Specifications = tbxspecifications.Text ?? string.Empty;
            materialInput.Unit_Name = tbxunit.Text ?? string.Empty;
            
            // 设置物料ID和单位ID
            materialInput.Material_Id = _selectedMaterialId;
            materialInput.Unit_Id = _selectedUnitId;
            
            // 调试信息：显示所有字段的赋值情况
            Console.WriteLine("=== 控件原始值 ===");
            Console.WriteLine($"tbxid.Text: '{tbxid.Text}'");
            Console.WriteLine($"tbxsupplier.Text: '{tbxsupplier.Text}'");
            Console.WriteLine($"tbxProcurementName.Text: '{tbxProcurementName.Text}'");
            Console.WriteLine($"tbxorder.Text: '{tbxorder.Text}'");
            Console.WriteLine($"tbxordername.Text: '{tbxordername.Text}'");
            Console.WriteLine($"tbxmaterialid.Text: '{tbxmaterialid.Text}'");
            Console.WriteLine($"tbxmaterialname.Text: '{tbxmaterialname.Text}'");
            Console.WriteLine($"tbxspecifications.Text: '{tbxspecifications.Text}'");
            Console.WriteLine($"tbxunit.Text: '{tbxunit.Text}'");
            Console.WriteLine($"tbxwarehousename.Text: '{tbxwarehousename.Text}'");
            Console.WriteLine($"tbxpeople.Text: '{tbxpeople.Text}'");
            Console.WriteLine("==================");
            
            Console.WriteLine("=== 赋值结果 ===");
            Console.WriteLine($"PurchaseOrdersNumber: '{tbxid.Text}' -> '{materialInput.PurchaseOrdersNumber}'");
            Console.WriteLine($"SupplierName: '{tbxsupplier.Text}' -> '{materialInput.SupplierName}'");
            Console.WriteLine($"PurchaseOrdersName: '{tbxProcurementName.Text}' -> '{materialInput.PurchaseOrdersName}'");
            Console.WriteLine($"PurchaseOrdersName_Id: '{tbxProcurementName.Text}' -> {materialInput.PurchaseOrdersName_Id}");
            Console.WriteLine($"IncomingNumber: '{tbxorder.Text}' -> '{materialInput.IncomingNumber}'");
            Console.WriteLine($"IncomingName: '{tbxordername.Text}' -> '{materialInput.IncomingName}'");
            Console.WriteLine($"IncomingName_Id: '{tbxordername.Text}' -> {materialInput.IncomingName_Id}");
            Console.WriteLine($"MaterialNumber: '{tbxmaterialid.Text}' -> '{materialInput.MaterialNumber}'");
            Console.WriteLine($"MaterialName: '{tbxmaterialname.Text}' -> '{materialInput.MaterialName}'");
            Console.WriteLine($"Specifications: '{tbxspecifications.Text}' -> '{materialInput.Specifications}'");
            Console.WriteLine($"Unit_Name: '{tbxunit.Text}' -> '{materialInput.Unit_Name}'");
            Console.WriteLine($"Material_Id: {_selectedMaterialId} -> {materialInput.Material_Id}");
            Console.WriteLine($"Unit_Id: {_selectedUnitId} -> {materialInput.Unit_Id}");
            Console.WriteLine("==================");

            // 解析数量
            if (!int.TryParse(dtpcount.Text, out int quantity))
            {
                MessageBox.Show("入库数量必须是有效的整数!", "校验失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            materialInput.Quantity = quantity;

            // 设置日期 - 直接使用当前时间
            materialInput.StartDate = DateTime.Now;
            materialInput.EndDate = DateTime.Now.AddDays(30); // 结束日期设为30天后
            
            // 调试信息：显示日期值
            Console.WriteLine($"StartDate: {materialInput.StartDate}");
            Console.WriteLine($"EndDate: {materialInput.EndDate}");

            // 设置仓库信息
            materialInput.Warehouse_Name = tbxwarehousename.Text ?? string.Empty;
            materialInput.Warehouse_Area=tbxarea.Text ?? string.Empty;
            materialInput.Storage_location=tbxlocation.Text ?? string.Empty;
            materialInput.Principal = tbxpeople.Text;
            
            // 设置仓库ID和库区ID
            materialInput.Warehouse_Id = _selectedWarehouseId;
            materialInput.AreaId = _selectedAreaId;
            
            // 设置其他字段的默认值
            materialInput.Material_InOutType = 2; // 入库类型
            materialInput.Warehouse_Area = string.Empty; // 库区名称，暂时为空
            materialInput.Storage_location = string.Empty; // 库位，暂时为空
            
            // 调试信息：显示仓库信息
            Console.WriteLine($"Warehouse_Name: {tbxwarehousename.Text} -> {materialInput.Warehouse_Name}");
            Console.WriteLine($"Warehouse_Id: {_selectedWarehouseId} -> {materialInput.Warehouse_Id}");
            Console.WriteLine($"AreaId: {_selectedAreaId} -> {materialInput.AreaId}");
            Console.WriteLine($"Principal: {tbxpeople.Text} -> {materialInput.Principal}");

            // 解析批次号
            if (!string.IsNullOrWhiteSpace(tbxbatch.Text) && int.TryParse(tbxbatch.Text, out int batch))
            {
                materialInput.Batch = batch;
            }

            // 设置状态为启用
            materialInput.Status = false;
            
            // 最终调试信息：显示所有重要字段的赋值情况
            Console.WriteLine("=== 最终赋值结果 ===");
            Console.WriteLine($"WarehouseReceiptNumber: {materialInput.WarehouseReceiptNumber}");
            Console.WriteLine($"WarehouseReceiptName: {materialInput.WarehouseReceiptName}");
            Console.WriteLine($"WarehousingDate: {materialInput.WarehousingDate}");
            Console.WriteLine($"PurchaseOrdersNumber: {materialInput.PurchaseOrdersNumber}");
            Console.WriteLine($"PurchaseOrdersName: {materialInput.PurchaseOrdersName}");
            Console.WriteLine($"SupplierName: {materialInput.SupplierName}");
            Console.WriteLine($"IncomingNumber: {materialInput.IncomingNumber}");
            Console.WriteLine($"IncomingName: {materialInput.IncomingName}");
            Console.WriteLine($"Quantity: {materialInput.Quantity}");
            Console.WriteLine($"StartDate: {materialInput.StartDate}");
            Console.WriteLine($"EndDate: {materialInput.EndDate}");
            Console.WriteLine($"MaterialNumber: {materialInput.MaterialNumber}");
            Console.WriteLine($"MaterialName: {materialInput.MaterialName}");
            Console.WriteLine($"Specifications: {materialInput.Specifications}");
            Console.WriteLine($"Unit_Name: {materialInput.Unit_Name}");
            Console.WriteLine($"Material_Id: {materialInput.Material_Id}");
            Console.WriteLine($"Unit_Id: {materialInput.Unit_Id}");
            Console.WriteLine($"Warehouse_Name: {materialInput.Warehouse_Name}");
            Console.WriteLine($"Warehouse_Id: {materialInput.Warehouse_Id}");
            Console.WriteLine($"AreaId: {materialInput.AreaId}");
            Console.WriteLine($"Principal: {materialInput.Principal}");
            Console.WriteLine($"Status: {materialInput.Status}");
            Console.WriteLine("==================");

            // 提交请求
            await Add(materialInput);
        }

        /// <summary>
        /// 从文本中提取ID值
        /// </summary>
        /// <param name="text">包含ID的文本</param>
        /// <returns>提取的ID值，如果失败返回0</returns>
        private int GetIdFromText(string text)
        {
            try
            {
                // 如果文本本身就是数字，直接解析
                if (int.TryParse(text, out int id))
                    return id;
                
                // 如果文本包含数字，尝试提取
                var numbers = System.Text.RegularExpressions.Regex.Matches(text, @"\d+");
                if (numbers.Count > 0 && int.TryParse(numbers[0].Value, out int extractedId))
                    return extractedId;
                
                // 如果都失败了，返回0
                return 0;
            }
            catch
            {
                return 0;
            }
        }

      

        /// <summary>
        /// 设置日期控件的值
        /// </summary>
        /// <param name="dateControl">日期控件</param>
        /// <param name="dateTime">要设置的日期时间</param>
        private void SetDateControlValue(CCWin.SkinControl.SkinDateTimePicker dateControl, DateTime dateTime)
        {
            try
            {
                // 尝试设置Value属性
                var valueProperty = dateControl.GetType().GetProperty("Value");
                if (valueProperty != null)
                {
                    valueProperty.SetValue(dateControl, dateTime);
                    return;
                }
                
                // 尝试设置Text属性
                var textProperty = dateControl.GetType().GetProperty("Text");
                if (textProperty != null)
                {
                    textProperty.SetValue(dateControl, dateTime.ToString("yyyy-MM-dd"));
                    return;
                }
            }
            catch
            {
                // 如果设置失败，忽略错误
            }
        }

        /// <summary>
        /// 发送POST请求
        /// </summary>
        private async Task Add(AddMaterialInputDtos materialInputData)
        {
            try
            {
                // 初始化API客户端
                var apiClient = new ApiClient(MaterialAppConfig.ApiBaseUrl);

                var response = await apiClient.PostAsync<AddMaterialInputDtos, ApiResponse<string>>(
                    endpoint: "Material/AddMaterial_InOut",
                    data: materialInputData
                );

                if (response != null && response.code == 200)
                {
                    MessageBox.Show("物料入库添加成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    
                    // 设置成功标志，通知父窗体需要刷新数据
                    this.Tag = "Success";
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    MessageBox.Show($"提交失败: {response?.message ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"提交失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        ///// <summary>
        ///// 清空表单
        ///// </summary>
        private void ClearForm()
        {
            tbxnumber.Text = "请输入";
            tbxname.Text = string.Empty;
            tbxProcurementName.Text = string.Empty;
            tbxid.Text = string.Empty;
            tbxsupplier.Text = string.Empty;
            tbxordername.Text = string.Empty;
            tbxorder.Text = string.Empty;
            tbxmaterialname.Text = string.Empty;
            tbxmaterialid.Text = string.Empty;
            tbxspecifications.Text = string.Empty;
            tbxunit.Text = string.Empty;
            tbxbatch.Text = string.Empty;
            dtpcount.Text = string.Empty;
            tbxwarehousename.Text = string.Empty;
            tbxpeople.Text = string.Empty;
            cbonumber.Checked = false;
            SetDateControlValue(dtpdate, DateTime.Now);
            SetDateControlValue(stpstart, DateTime.Now);
            SetDateControlValue(dtptime, DateTime.Now);
        }

        // 定义用于解析API响应的模型类
        public class ApiResponse<T>
        {
            public int code { get; set; }
            public string message { get; set; }
            public string jwt { get; set; }
            public T pageData { get; set; }
            public T data { get; set; }
            public int totalCount { get; set; }
            public int totalPages { get; set; }
        }
        
        
    }
}
